{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4fa0ce4484f8"
   },
   "source": [
    "##### Copyright 2020 Google"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "906e07f6e562"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e6d108d2b320"
   },
   "source": [
    "# Fermi-Hubbard experiment example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8d9dec56909c"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.example.org/cirq/experiments/fermi_hubbard/experiment_example\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/ReCirq/blob/master/docs/fermi_hubbard/experiment_example.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/ReCirq/blob/master/docs/fermi_hubbard/experiment_example.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/ReCirq/docs/fermi_hubbard/experiment_example.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9ec578c1796c"
   },
   "source": [
    "This notebook demonstrates how to define, execute, and plot the results of a single instance of [the Fermi-Hubbard experiment](https://arxiv.org/abs/2010.07965). We show how to run the experiment using a Cirq simulator and a quantum processor through Google's Quantum Computing Service.\n",
    "\n",
    "The Fermi-Hubbard model on a one-dimensional lattice of $L$ sites with open boundary conditions is defined by the Hamiltonian\n",
    "\n",
    "$$\n",
    "H = - J \\sum_{j = 1}^{L - 1} \\sum_{\\nu = \\uparrow, \\downarrow} c_{j, \\nu}^\\dagger c_{j + 1, \\nu} + \\text{h.c.} + U \\sum_{j = 1}^{L} n_{j, \\uparrow} n_{j, \\downarrow} + \\sum_{j = 1}^{L} \\sum_{\\nu = \\uparrow, \\downarrow} \\epsilon_{j, \\nu} n_{j, \\nu} \n",
    "$$\n",
    "\n",
    "where $c_{j, \\nu}$ ($c_{j, \\nu}^\\dagger$) are the fermionic annihilation (creation) operators associated to site number $j$ and spin state $\\nu$, and $n_{j, \\nu} = c_{j, \\nu}^\\dagger c_{j, \\nu}$ are the number operators. The *hopping term* with coefficient $J$ describes particles tunneling between neighboring sites, the *onsite interaction term* with coefficient $U$ introduces an energy difference for doubly occupied sites, and the term $\\epsilon_{j, \\nu}$ represents spin-dependent local potentials. \n",
    "\n",
    "Our goal in this experiment is to compute the charge and spin densities which are defined as the sum and difference of the spin-up and spin-down particle densities, respectively\n",
    "\n",
    "$$\n",
    "\\rho_{j}^{\\pm} = \\langle n_{j, \\uparrow} \\rangle \\pm \\langle n_{j, \\downarrow} \\rangle,\n",
    "$$\n",
    "\n",
    "after simulating the Fermi-Hubbard model for some evolution time. Here, the expectation is taken with respect to the extended Hamiltonian\n",
    "\n",
    "$$\n",
    "H' = H + V \\sum_{j = 1}^{L - 1} \\sum_{\\nu = \\uparrow, \\downarrow}  n_{j, \\nu} n_{j + 1, \\nu}\n",
    "$$\n",
    "\n",
    "which has an additional interaction term between neighboring fermionic sites. This enables extended simulations beyond the standard Fermi-Hubbard model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b3600ee25c8e"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "33160e02c33d"
   },
   "source": [
    "We first install ReCirq which contains code for running Fermi-Hubbard experiments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c492bfc73689"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import recirq\n",
    "except ImportError:\n",
    "    print(\"Installing ReCirq...\")\n",
    "    !pip install git+https://github.com/quantumlib/recirq --quiet\n",
    "    print(\"Installed ReCirq!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8eef2cc5d237"
   },
   "source": [
    "To track the progress of simulating experiments, we use the `tqdm` package."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1b16b470c4c5"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import ipywidgets\n",
    "except ImportError:\n",
    "    !pip install ipywidgets --quiet\n",
    "    !jupyter nbextension enable --py widgetsnbextension --sys-prefix"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "46dbcc43d1e3"
   },
   "source": [
    "We can now import Cirq and the `fermi_hubbard` module from ReCirq."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3da3b5a75363"
   },
   "outputs": [],
   "source": [
    "import cirq\n",
    "\n",
    "from recirq import fermi_hubbard\n",
    "from recirq.fermi_hubbard import publication\n",
    "\n",
    "# Hide numpy warnings\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1aecebe2b044"
   },
   "source": [
    "## Experiment parameters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d4d79e011a84"
   },
   "source": [
    "The first step is to decide on exact experiment parameters including problem Hamiltonian, initial state description, as well as a mapping from fermions to qubits on the device. Once we have this information, we can create circuits and run the experiment."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9412a40fb274"
   },
   "source": [
    "### Qubit layout"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5fd885507094"
   },
   "source": [
    "We will simulate the Fermi-Hubbard model on $L = 8$ sites. Each site is represented by two qubits due to the two spin states, so we need a total of $16$ qubits to simulate the experiment.\n",
    "\n",
    "The function `rainbow23_layouts` returns a set of $16$-qubit subgrids of the Google Rainbow processor. \n",
    "\n",
    "> *Note*: We use multiple layouts to average results over different qubit assignments. One the quantum processor, this cancels some of the statistical errors which occur from calibration to calibration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9a677d1ac39c"
   },
   "outputs": [],
   "source": [
    "\"\"\"Get all layouts for 8 sites on a 23-qubit subgrid of the Google Rainbow processor.\"\"\"\n",
    "layouts = publication.rainbow23_layouts(sites_count=8)\n",
    "print(f\"There are {len(layouts)} total qubit layouts.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "343ff5aa9b85"
   },
   "source": [
    "We can see an example layout by printing out its text diagram."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "d47795056271"
   },
   "outputs": [],
   "source": [
    "\"\"\"Display an example layout.\"\"\"\n",
    "print(layouts[0].text_diagram())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f8c5c23d190e"
   },
   "source": [
    "The layout indicates the site index $j$ and spin state $\\nu$, as well as which `cirq.GridQubit` on the Rainbow processor this combination of $(j, \\nu)$ is encoded into. One can choose a different layout in the previous cell to see how the configurations vary."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a7e87bd5fd64"
   },
   "source": [
    "### Problem parameters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e8d103db8d2f"
   },
   "source": [
    "Let's use the Hamiltonian with uniform $J = 1$ and $U = 2$ on each site, initial state prepared as a ground state of a non-interacting Hamiltonian with trapping potential of a Gaussian shape, Trotter step size equal to 0.3, and two particles per chain. The problem parameters with this initial state can be prepared with the pre-defined function `trapping_instance`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "4434177bb891"
   },
   "outputs": [],
   "source": [
    "\"\"\"Get FermiHubbardParameters (problem descriptions) for each qubit layout with the above parameters.\"\"\"\n",
    "parameters = [\n",
    "    publication.trapping_instance(\n",
    "        layout, u=2, dt=0.3, up_particles=2, down_particles=2\n",
    "    ) \n",
    "    for layout in layouts\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fa1698136d4b"
   },
   "source": [
    "> Other configurations which support site-dependent $U$ and $J$ coefficients can be prepared by creating instances of the `fermi_hubbard.FermiHubbardParameters` data class explicitly."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7012bc6bf445"
   },
   "source": [
    "The results are instances of the `FermiHubbardParameters` data class for each layout. This data class uniquely defines the configuration to run and contains information such as the Hamiltonian, initial state, layout, and time step. Below, we display these values for an example element of `parameters`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "a4596869c147"
   },
   "outputs": [],
   "source": [
    "\"\"\"Display the Hamiltonian for an example problem description.\"\"\"\n",
    "parameters_example = parameters[0]\n",
    "print(parameters_example.hamiltonian)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a48d366d6bbb"
   },
   "source": [
    "We can also see the initial state:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "055b05e86460"
   },
   "outputs": [],
   "source": [
    "parameters_example.initial_state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4fe383f88a85"
   },
   "source": [
    "And the time step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9b92d6c6fc36"
   },
   "outputs": [],
   "source": [
    "parameters_example.dt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b3eca713f124"
   },
   "source": [
    "## Circuits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "048b3f2dfc5e"
   },
   "source": [
    "One can directly run an experiment from a `FermiHubbardParameters` instance (which we will do in the next section). However, it is illustrative to construct the circuits to see how the Fermi-Hubbard execution works."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e059a98daabe"
   },
   "source": [
    "### Circuit creation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "831a9f5b55bb"
   },
   "source": [
    "To create a circuit from a description of a problem, the function `fermi_hubbard.create_circuits` can be used. This function inputs a `FermiHubbardParameters` instance (i.e., a problem description) and number of Trotter steps. It returns circuits for constructing the initial state, simulating time-evolution via a number of Trotter steps, and measuring to compute observables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "0e3d1c97811e"
   },
   "outputs": [],
   "source": [
    "\"\"\"Create circuits from a problem description.\"\"\"\n",
    "initial, trotter, measurement = fermi_hubbard.create_circuits(parameters_example, trotter_steps=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8e8154175976"
   },
   "source": [
    "Below, we display the complete circuit to execute which is a sum of the three component circuits above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "77a759e93d1c"
   },
   "outputs": [],
   "source": [
    "\"\"\"Display the total circuit to execute.\"\"\"\n",
    "circuit = initial + trotter + measurement\n",
    "circuit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bdadb266fcf4"
   },
   "source": [
    "> *Note*: For a deeper explanation of these circuits and the gates used in them, see the [Fermi-Hubbard experiment paper](https://arxiv.org/abs/2010.07965)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "94fb4ce74e44"
   },
   "source": [
    "### Circuit decomposition"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "35652ae73898"
   },
   "source": [
    "The circuit above is constructed using gates which are not native to Google hardware, for example `cirq.FSim` or `cirq.CZ` with arbitrary exponent. To run these circuits on Google hardware, we have to convert them into native operations. For the Fermi-Hubbard experiment, a special converter called `ConvertToNonUniformSqrtIswapGates` is provided.\n",
    "\n",
    "This converter has the ability to decompose gates to $\\sqrt{\\small \\mbox{iSWAP}}$ both perfectly (i.e., without noise) and with unitary parameters deviating from the perfect ones and varying between qubit pairs. The function `ideal_sqrt_iswap_converter` creates an instance of the noiseless converter which decomposes $\\sqrt{\\small \\mbox{iSWAP}}$ gates exactly as `cirq.FSim(π/4, 0)`. The function `google_sqrt_iswap_converter` creates an instance of the noisy converter which approximates the average values on Rainbow processor (which are about `cirq.FSim(π/4, π/24)` on each two-qubit pair).\n",
    "\n",
    "Below we show an example of the perfect decomposition into the $\\sqrt{\\small \\mbox{iSWAP}}$ gate set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c6fc02191335"
   },
   "outputs": [],
   "source": [
    "\"\"\"Convert the circuit to native hardware gates perfectly (without noise).\"\"\"\n",
    "publication.ideal_sqrt_iswap_converter().convert(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2186b86e188f"
   },
   "source": [
    "We will consider both ideal and noisy decompositions when executing the experiment below."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f8754d2cccc0"
   },
   "source": [
    "## Cirq simulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2c642750808b"
   },
   "source": [
    "This section demonstrates how to simulate experiments using Cirq simulator. We will simulate the evolution from $0$ to $10$ Trotter steps. Physically, this corresponds to an evolution time of $t = 3 \\hbar / J$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "d7eafc63a473"
   },
   "outputs": [],
   "source": [
    "\"\"\"Set the number of Trotter steps to simulate.\"\"\"\n",
    "trotter_steps = range(10 + 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a2348762745b"
   },
   "source": [
    "### Ideal"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "134e7e4ef033"
   },
   "source": [
    "As mentioned above, we can use the `ideal_sqrt_iswap_converter` to convert circuits perfectly into the $\\sqrt{\\small \\mbox{iSWAP}}$ gate set. The Fermi-Hubbard project provides `ConvertingSampler` that converts circuits before executing ands sampling from them. We get an ideal sampler below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "47578126a344"
   },
   "outputs": [],
   "source": [
    "\"\"\"Get an ideal sampler to simulate experiments.\"\"\"\n",
    "ideal_sampler = fermi_hubbard.ConvertingSampler(\n",
    "    cirq.Simulator(), publication.ideal_sqrt_iswap_converter().convert\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "59c49d675ffc"
   },
   "source": [
    "We can now run experiments using the `run_experiment` function. This function takes the parameters of a problem, a sampler, and a list of Trotter steps to simulate. Below, we provide the problem parameters defined on each $16$ qubit layout of the Rainbow processor and simulate the experiments using ten Trotter steps and the `ideal_sampler`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "76790b284d7a"
   },
   "outputs": [],
   "source": [
    "\"\"\"Run the experiments on a perfect simulator for each qubit layout.\"\"\"\n",
    "from tqdm.notebook import tqdm\n",
    "\n",
    "with tqdm(range(len(parameters) * len(trotter_steps))) as progress:\n",
    "    experiments = [\n",
    "        fermi_hubbard.run_experiment(\n",
    "            params, \n",
    "            trotter_steps, \n",
    "            ideal_sampler, \n",
    "            post_run_func=lambda *_: progress.update()\n",
    "        )\n",
    "        for params in parameters\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "632db9baccf6"
   },
   "source": [
    "The output of `run_experiment` is an instance of the `ExperimentResult` data class. A series of experiments for the same problem instance on different qubit layouts can be post-processed with the help of the `InstanceBundle` class. This class takes care of averaging results over qubits layouts, re-scaling the data by comparing against a reference run (perfect simulation in this case), and extracting various quantities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "e4d0097312f1"
   },
   "outputs": [],
   "source": [
    "\"\"\"Post-process the experimental data for all qubit layouts.\"\"\"\n",
    "bundle = fermi_hubbard.InstanceBundle(experiments)\n",
    "bundle.cache_exact_numerics()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9891943f0181"
   },
   "source": [
    "A number of quantities of interest can be accessed from an `InstanceBundle`, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9a164fb39539"
   },
   "outputs": [],
   "source": [
    "\"\"\"Show quantities which can be accessed from an InstanceBundle.\"\"\"\n",
    "for quantity_name in bundle.quantities:\n",
    "    print(quantity_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0cf7c52849f2"
   },
   "source": [
    "Each quantity can be converted to a pandas `DataFrame` using the `quantity_data_frame` function. Our main goal in simulating the Fermi-Hubbard model was to compute the charge and spin densities\n",
    "\n",
    "$$\n",
    "\\rho_{j}^{\\pm} = \\langle n_{j, \\uparrow} \\rangle \\pm \\langle n_{j, \\downarrow} \\rangle .\n",
    "$$\n",
    "\n",
    "We can get a `DataFrame` for the `\"charge_spin_density\"` quantity as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "995a0ad9b1b9"
   },
   "outputs": [],
   "source": [
    "\"\"\"Example of getting a DataFrame from a quantity.\"\"\"\n",
    "charge_spin_density, _, _ = fermi_hubbard.quantity_data_frame(bundle, \"charge_spin_density\")\n",
    "charge_spin_density.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aad1d61619c2"
   },
   "source": [
    "This data frame contains the value, standard error, and standard deviation of the `\"charge_spin_density\"` quantity at each site for each time (Trotter step). For convenience, this quantity (and others) can be plotted with the `fermi_hubbard.plot_quantity` helper function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fda88e19e080"
   },
   "outputs": [],
   "source": [
    "\"\"\"Plot the charge spin density.\"\"\"\n",
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_density\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6afd21793718"
   },
   "source": [
    "This plotting function automatically adjusts the appearance of plots according to the data being plotted. We illustrate this by plotting the `\"charge_spin_spreading\"` below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "7f4a02dffcd6"
   },
   "outputs": [],
   "source": [
    "\"\"\"Plot the charge spin spreading.\"\"\"\n",
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_spreading\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "84071bf65186"
   },
   "source": [
    "One can compare these plots to Figure 2 of the [Fermi-Hubbard experiment paper](https://arxiv.org/abs/2010.07965)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6ae59a047944"
   },
   "source": [
    "### Parasitic controlled-phase"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fc7a70b65c0e"
   },
   "source": [
    "We now run the same experiment but with the `google_sqrt_iswap_converter`. As mentioned, this decomposes $\\sqrt{\\small \\mbox{iSWAP}}$ gates imperfectly as `cirq.FSim(π/4, π/24)` which is close to the average value of the parasitic controlled phase on the Rainbow processor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "70addbcd7b40"
   },
   "outputs": [],
   "source": [
    "\"\"\"Run the experiments on a noisy simulator for each qubit layout.\"\"\"\n",
    "parasitic_sampler = fermi_hubbard.ConvertingSampler(\n",
    "    cirq.Simulator(), publication.google_sqrt_iswap_converter().convert\n",
    "    )\n",
    "\n",
    "with tqdm(range(len(parameters) * len(trotter_steps))) as progress:\n",
    "    experiments = [\n",
    "        fermi_hubbard.run_experiment(\n",
    "            params, \n",
    "            trotter_steps, \n",
    "            parasitic_sampler, \n",
    "            post_run_func=lambda *_: progress.update()\n",
    "        )\n",
    "        for params in parameters\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f6b1762ea69a"
   },
   "source": [
    "As above, we can post-process the data using an `InstanceBundle` and plot quantities of interest using the `plot_quantity` helper function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6e4a08904282"
   },
   "outputs": [],
   "source": [
    "\"\"\"Post-process the experimental data for all qubit layouts.\"\"\"\n",
    "bundle = fermi_hubbard.InstanceBundle(experiments)\n",
    "bundle.cache_exact_numerics()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6000b7313faa"
   },
   "source": [
    "We first plot the `\"charge_spin_density\"`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5cdd33c4f506"
   },
   "outputs": [],
   "source": [
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_density\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f251a67e70ff"
   },
   "source": [
    "And plot the `\"charge_spin_spreading\"` as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ca54ed0803cd"
   },
   "outputs": [],
   "source": [
    "\"\"\"Plot the charge spin spreading.\"\"\"\n",
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_spreading\", show_std_error=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ad8505cfee8c"
   },
   "source": [
    "One can compare these to the simulation with exact decompositions above to see the effect of the parasitic controlled phase."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9423ead536da"
   },
   "source": [
    "# Execution on Google's Quantum Computing Service"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "373ada3ed59f"
   },
   "source": [
    "In order to run an experiment on Google's QCS, a `QuantumEngine` sampler is needed. To create an engine sampler, an environment variable `GOOGLE_CLOUD_PROJECT` must be present and set to a valid Google Cloud Platform project identifier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "aa516db560a5"
   },
   "outputs": [],
   "source": [
    "\"\"\"Get an engine sampler.\"\"\"\n",
    "import os\n",
    "\n",
    "if \"GOOGLE_CLOUD_PROJECT\" in os.environ:\n",
    "    engine_sampler = cirq.google.get_engine_sampler(\n",
    "        processor_id=\"rainbow\", gate_set_name=\"sqrt_iswap\"\n",
    "    )\n",
    "else:\n",
    "    # Use the simulator as a backup.\n",
    "    engine_sampler = cirq.Simulator()\n",
    "\n",
    "# Get a sampler for the Fermi-Hubbard experiment.\n",
    "google_sampler = fermi_hubbard.ConvertingSampler(\n",
    "    engine_sampler, publication.google_sqrt_iswap_converter().convert\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "24c6fbf30a16"
   },
   "source": [
    "Now that we are running on a quantum computer, we follow good experimental practice and save the results on disk as soon as each experiment finishes using the `fermi_hubbard.save_experiment` function. Although rare, remote operation may fail for various reasons. More advanced execution workflow might include error handling, experiment pause and continuation, etc., which we omit here for simplicity.\n",
    "\n",
    "> *Note*: We do not include Floquet calibration, the calibration technique described in the Supplementary Information of the [Fermi-Hubbard experiment paper](https://arxiv.org/abs/2010.07965), when executing the experiments below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1210216b0c5e"
   },
   "outputs": [],
   "source": [
    "\"\"\"Run the experiments on Google's QCS and save the results.\"\"\"\n",
    "# Directory to save results in.\n",
    "results_dir = \"trapping\"\n",
    "\n",
    "with tqdm(range(len(layouts) * len(trotter_steps))) as progress:\n",
    "    for index, params in enumerate(parameters):\n",
    "        experiment = fermi_hubbard.run_experiment(\n",
    "            params, \n",
    "            trotter_steps, \n",
    "            google_sampler, \n",
    "            post_run_func=lambda *_: progress.update()\n",
    "        )\n",
    "        \n",
    "        fermi_hubbard.save_experiment(\n",
    "            experiment, f\"{results_dir}/trapping_{index + 1}.json\"\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b53e9d2da595"
   },
   "source": [
    "We can now load the results using `fermi_hubbard.load_experiment`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "d0f3e7f9ec2c"
   },
   "outputs": [],
   "source": [
    "\"\"\"Load experimental results.\"\"\"\n",
    "experiments = [\n",
    "    fermi_hubbard.load_experiment(f\"{results_dir}/trapping_{index + 1}.json\") \n",
    "    for index in range(len(parameters))\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "41dc22ca1de3"
   },
   "source": [
    "When post-processing experimental data from hardware, we include effects due the the parasitic controlled phase as shown below. The value $\\phi = 0.138$ was the approximate value of the parasitic controlled phase at the time when the experimental results in the paper were collected."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "f8f5b19d9856"
   },
   "outputs": [],
   "source": [
    "\"\"\"Post-process the experimental data for all qubit layouts.\"\"\"\n",
    "bundle = fermi_hubbard.InstanceBundle(\n",
    "    experiments,numerics_transform=publication.parasitic_cphase_compensation(0.138)\n",
    ")\n",
    "bundle.cache_exact_numerics()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "223f8a2ff630"
   },
   "source": [
    "We can now visualize these results using the same plotting functions from above. Here we show the standard deviation of results in the plots."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "dba1355998ba"
   },
   "outputs": [],
   "source": [
    "\"\"\"Plot the charge spin density.\"\"\"\n",
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_density\", show_std_error=True);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "030ef06326e3"
   },
   "outputs": [],
   "source": [
    "\"\"\"Plot the charge spin spreading.\"\"\"\n",
    "fermi_hubbard.plot_quantity(bundle, \"charge_spin_spreading\", show_std_error=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ccebcf0cf19a"
   },
   "source": [
    "If Google's QCS was used, these experimental results can be compared to previous experiments executed on simulators."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "experiment_example.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
